<template>
  <div>
    <a-spin :spinning="spinning">
      <div ref="chartContainer" style="width: 100%; height: 70vh"></div>
    </a-spin>
  </div>
</template>
<script setup>
import * as echarts from "echarts";
import "echarts-gl";
import html2canvas from "html2canvas";
import WellAnalysis from '@/api/v3/mechanical.js'
import WellSurvey from "@/api/survey/survey.js";
import { salvageFile } from "@/api/file/file.js";
import useApp from "@/hooks";
const { $ } = useApp();
const spinning = ref(false);
const chartContainer = ref(null);
const chart = ref();
const holeData = ref([]);
const svgUrl = ref();
const coord = ref([]);
const lithologyImg = ref([]);
const props = defineProps({
  echartsData: Object,
  pass: {
    type: Array,
    default: [],
  },
});
onMounted(() => {
  // getData()
});
watch([() => props.echartsData, () => props.pass], () => {
  //清空画板
  console.log("props.echartsData", props.echartsData);
  if (chart.value != undefined) {
    chart.value.clear();
  }
  getData();
});
function getData() {
  var wellId = localStorage.getItem("salvageWellId"); //bucketName
  // var fileId = localStorage.getItem("salvageFileId");
  // // console.log('fileId', fileId);
  // if (fileId == "undefined") {
  //   spinning.value = false;
  // } else {
  //   spinning.value = true;
  //   let isAddPoint = localStorage.getItem("isSalPoint")
  //   console.log('isAddPoint', isAddPoint);
  //   //每隔1米测深提供一个xyz轴
  //   WellAnalysis.interWell(wellId, 1, isAddPoint).then((res) => {
  //     // console.log("interWell", res);
  //     holeData.value = res.content;
  //     renderChart(holeData.value, svgUrl.value);
  //   });
  // }
  WellSurvey.latestSurvey(wellId).then(response => {
    console.log("response", response);
    if (response.wellId) {
      console.log('测井数据存在');
      spinning.value = true;
      let isAddPoint = response.skew
      //每隔1米测深提供一个xyz轴
      WellAnalysis.interWell(wellId, 1, isAddPoint).then((res) => {
        // console.log("interWell", res);
        holeData.value = res.content;
        renderChart(holeData.value, svgUrl.value);
      });
    } else {
      console.log('测井数据不存在');
      spinning.value = false;
    }
  })
}
// 获取岩性信息
function getLithList(data) {
  coord.value = [];
  data.forEach((res) => {
    const pixel = chart.value.convertToPixel("grid", [0, -res.endDepth]);
    const headPixel = chart.value.convertToPixel("grid", [0, -res.startDepth]);
    coord.value.push({
      pixelCoord: pixel,
      headPixelCoord: headPixel,
      svgUrl: res.svg,
    });
  });
  chart.value.clear();
  renderChart(holeData.value, coord.value);
}
defineExpose({ getLithList });

function renderChart(dataRows, formLithology) {
  spinning.value = true;
  const data = [[0, 0, 0]];
  const drill = [];
  const casing = [];
  const risk = [];
  const passResult = [];
  let lithologySvg = [];

  lithologyImg.value = [];
  const depth = dataRows[dataRows.length - 1].true_vertical_depth;
  dataRows.forEach((element) => {
    const x = element.north;
    const y = element.east;
    const z = -element.true_vertical_depth;
    data.push([x, y, z]);
    // console.log(data)
  });
  const divElement = chartContainer.value;
  chart.value = echarts.init(chartContainer.value);
  //岩性信息
  let svgWidth = 20;
  let t = [];
  formLithology?.forEach((item) => {
    const step = parseInt((item.pixelCoord[1] - item.headPixelCoord[1]) / svgWidth) - 1;
    for (let i = 0; i < step; i++) {
      t.push(
        {
          type: "image",
          style: {
            image: item.svgUrl,
            x: item.pixelCoord[0] - 100,
            y: item.pixelCoord[1] - (i + 1) * svgWidth,
            width: 100,
            height: svgWidth,
            opacity: 0.9,
          },
        },
        {
          type: "image",
          style: {
            image: item.svgUrl,
            x: item.pixelCoord[0],
            y: item.pixelCoord[1] - (i + 1) * svgWidth,
            width: 100,
            height: svgWidth,
            opacity: 0.9,
          },
        }
      );
    }
    t.push(
      {
        type: "image",
        style: {
          image: item.svgUrl,
          x: item.pixelCoord[0] - 100,
          y: item.headPixelCoord[1],
          width: 100,
          height: svgWidth,
          opacity: 0.9,
        },
      },
      {
        type: "image",
        style: {
          image: item.svgUrl,
          x: item.pixelCoord[0],
          y: item.headPixelCoord[1],
          width: 100,
          height: svgWidth,
          opacity: 0.9,
        },
      },
      {
        type: "image",
        style: {
          image: item.svgUrl,
          x: item.pixelCoord[0] - 100,
          y: item.headPixelCoord[1] + 20,
          width: 100,
          height: svgWidth,
          opacity: 0.9,
        },
      },
      {
        type: "image",
        style: {
          image: item.svgUrl,
          x: item.pixelCoord[0],
          y: item.headPixelCoord[1] + 20,
          width: 100,
          height: svgWidth,
          opacity: 0.9,

        },
      }
    );
    lithologyImg.value = t;
    console.log("------lithologyImg.value------", lithologyImg.value);
    // console.log(lithologyImg.value);
  });

  //风险井段
  // props.echartsData?.wellRiskSectionList?.forEach((res) => {
  //   risk.push([
  //     {
  //       name: res.stratumName,
  //       yAxis: -res.start,
  //     },
  //     {
  //       yAxis: -res.end,
  //     },
  //   ]);
  // });
  // const riskRange = {
  //   itemStyle: {
  //     color: "rgba(255, 173, 177, 0.4)",
  //   },
  //   label: {
  //     show: true,
  //     position: "right", // 将 label 放在区域图的最右侧
  //     offset: [-120, 0], // 设置 label 的偏移量
  //   },
  //   data: [...risk],
  // };

  // 钻头
  props.echartsData.drillList.forEach((res) => {
    // console.log('钻头', res);
    let drillData = data.filter((e) => e[2] >= -res.deep);
    drill.push({
      type: "line",
      data: drillData.length == 1 ? [[0, 0, 0], [0, 0, -res.deep],] : drillData,
      // 变得圆滑
      smooth: true,
      // 隐藏折点
      symbolSize: 0.0000001,
      encode: {
        x: 0,
        y: 2,
        tooltip: [1, 2],
      },
      lineStyle: {
        opacity: 0.95,
        color: "#808080",
        width: res.outerDiameter * 0.2,
      },
    });
  });
  //添加风险井段内容
  // drill[drill.length - 1].markArea = riskRange;

  // 套管
  let numCasing = 1;
  props.echartsData.casingList.forEach((res) => {
    // console.log('套管', res);
    const numArray = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']
    let casingData = data.filter((e) => e[2] >= -res.deep);
    if (res.deep !== 0) {
      casing.push({
        type: "line",
        //判断 （套管终点到没到测井的起点）
        data: casingData.length == 1 ? [[0, 0, 0], [0, 0, -res.deep],] : casingData,
        // 变得圆滑
        smooth: true,
        // 隐藏折点
        showSymbol: false,
        name: res.name,
        endLabel: {
          show: true,
          lineHeight: 20,
          formatter: `{a|———>${numArray[numCasing]}开套管\n              垂深:${res.deep}m Φ${res.outerDiameter}mm}`,
          rich: {
            a: {
              fontWeight: 'bold', // 加粗
              fontSize: 16, // 字体大小
              color: "#1E90FF", // 文字颜色
            },
          },
        },
        encode: {
          x: 0,
          y: 2,
        },
        lineStyle: {
          opacity: 0.8,
          color: "#000000",
          width: res.outerDiameter * 0.2 - 10,
        },
      });
    }
    numCasing = numCasing + 1;
  });
  //通过性分析
  if (props.pass !== []) {
    props?.pass?.forEach((res) => {
      let passData = data.filter((e) => e[2] >= -res.deep);
      passResult.push({
        type: "line",
        symbol: "triangle",
        data: [[passData[passData.length - 1][0], -res.deep]],
        symbolSize: [25, 15],
        itemStyle: {
          color: "red", // 标志的颜色
          borderColor: "yellow", // 标志的边框颜色
          borderWidth: 3, // 标志的边框宽度
        },
      });
    });
  }

  //左视图
  const option = ref({
    animation: false,
    grid: {
      x: 50,
      y: 20,
      x2: 50,
      y2: 20,
      borderWidth: 1,
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
      },
      showContent: false,
    },

    xAxis: {
      type: "value",
      scale: true,
      min: -(depth / 2),
      max: depth / 2,
      axisLabel: "",
    },
    yAxis: {
      type: "value",
      scale: true,
      axisLabel: {
        formatter: function (value) {
          return Math.abs(value);
        },
      },
    },
    graphic: [...lithologyImg.value],
    series: [...drill, ...casing, ...passResult],
    //岩性图
  });
  chart.value.setOption(option.value);
  lithologyImg.value.splice(0, lithologySvg.length);
  spinning.value = false;
  canvaImg();
}
//截图
function canvaImg() {
  const formData = new FormData();
  html2canvas(chartContainer.value).then((canvas) => {
    const imageData = canvas.toDataURL("image/png");
    formData.append("chartType", "井身结构示意图");
    formData.append("file", imageData);
    formData.append("schemeId", localStorage.getItem("solutionId"));
    // console.log('截图', localStorage.getItem("solutionId"));
    salvageFile(formData).then((res) => {
      console.log("yes");
    });
  });
}
</script>
